package com.xszx.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xszx.config.PageRequest;
import com.xszx.dao.InOutDao;
import com.xszx.entity.GoodInOutInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.xszx.entity.MonthCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class InOutService {

    @Autowired
    private InOutDao inOutDao;
    //获取入库记录表
    public PageInfo<GoodInOutInfo> getInWarehouseRecord(PageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getSize());
        List<GoodInOutInfo> list = inOutDao.getInWarehouseRecord(pageRequest);
        return new PageInfo<>(list);
    }

    public PageInfo<GoodInOutInfo> getOutWarehouseRecord(PageRequest pageRequest) {
        List<GoodInOutInfo>  list = inOutDao.getOutWarehouseRecord(pageRequest);
        return new PageInfo<>(list);
    }


    public void exportOutWarehouseRecord(List<Integer> ids, String wnumber, String rcode,
                                         String rlocation, String gtype, String gbatch,
                                         String time, Boolean exportAll, OutputStream os) throws IOException {

// 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("出库记录");

        // 设置表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);

        // 设置数据行样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 定义表头
        String[] headers = {"序号", "仓库编号", "区域编号", "仓位位置", "货物批次", "货物类型", "出库数量", "出库时间","客户名称","所属公司","联系方式"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, 25 * 256); // 设置列宽
        }

        // 查询要导出的数据
        List<GoodInOutInfo> exportData;
        if (exportAll != null) {
            // 导出全部数据（根据搜索条件）
            exportData = inOutDao.getOutWarehouseRecordByConditions(wnumber, rcode, rlocation, gtype, gbatch, time);
        } else if (ids != null && !ids.isEmpty()) {
            // 导出选中的记录
            exportData = inOutDao.getOutWarehouseRecordByIds(ids);
        } else {
            // 无数据时返回空列表
            exportData = null;
        }

        // 写入数据
        if (exportData != null && !exportData.isEmpty()) {
            for (int i = 0; i < exportData.size(); i++) {
                GoodInOutInfo record = exportData.get(i);
                Row dataRow = sheet.createRow(i + 1);

                // 序号
                dataRow.createCell(0).setCellValue(i + 1);
                // 仓库编号
                dataRow.createCell(1).setCellValue(record.getWnumber());
                // 区域编号
                dataRow.createCell(2).setCellValue(record.getRcode());
                // 仓位位置
                dataRow.createCell(3).setCellValue(record.getRlocation());
                // 货物批次
                dataRow.createCell(4).setCellValue(record.getGbatch());
                // 货物类型
                dataRow.createCell(5).setCellValue(record.getGtype());
                // 出库数量
                dataRow.createCell(6).setCellValue(record.getGnum());
                // 出库时间
                dataRow.createCell(7).setCellValue(record.getTime());
                //客户名称
                dataRow.createCell(8).setCellValue(record.getClient().getClientName());
                //所属公司
                dataRow.createCell(9).setCellValue(record.getClient().getEnterprise());
                //联系方式
                dataRow.createCell(10).setCellValue(record.getClient().getClientPhone());

                // 应用数据样式
                for (int j = 0; j < headers.length; j++) {
                    dataRow.getCell(j).setCellStyle(dataStyle);
                }
            }
        }

        // 写入文件
        try {
            workbook.write(os);
        } finally {
            workbook.close();
        }
    }

    public void exportIntWarehouseRecord(List<Integer> ids, String wnumber, String rcode,
                                         String rlocation, String gtype, String gbatch,
                                         String time, Boolean exportAll, OutputStream os) throws IOException {

// 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("入库记录");

        // 设置表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);

        // 设置数据行样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 定义表头
        String[] headers = {"序号", "仓库编号", "区域编号", "仓位位置", "货物批次", "货物类型", "入库数量", "入库时间","客户名称","所属公司","联系方式"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, 25 * 256); // 设置列宽
        }

        // 查询要导出的数据
        List<GoodInOutInfo> exportData;
        if (exportAll != null) {
            // 导出全部数据（根据搜索条件）
            exportData = inOutDao.getIntWarehouseRecordByConditions(wnumber, rcode, rlocation, gtype, gbatch, time);
        } else if (ids != null && !ids.isEmpty()) {
            // 导出选中的记录
            exportData = inOutDao.getIntWarehouseRecordByIds(ids);
        } else {
            // 无数据时返回空列表
            exportData = null;
        }

        // 写入数据
        if (exportData != null && !exportData.isEmpty()) {
            for (int i = 0; i < exportData.size(); i++) {
                GoodInOutInfo record = exportData.get(i);
                Row dataRow = sheet.createRow(i + 1);

                // 序号
                dataRow.createCell(0).setCellValue(i + 1);
                // 仓库编号
                dataRow.createCell(1).setCellValue(record.getWnumber());
                // 区域编号
                dataRow.createCell(2).setCellValue(record.getRcode());
                // 仓位位置
                dataRow.createCell(3).setCellValue(record.getRlocation());
                // 货物批次
                dataRow.createCell(4).setCellValue(record.getGbatch());
                // 货物类型
                dataRow.createCell(5).setCellValue(record.getGtype());
                //入库时间
                dataRow.createCell(7).setCellValue(record.getTime());
                //客户名称
                dataRow.createCell(8).setCellValue(record.getClient().getClientName());
                //所属公司
                dataRow.createCell(9).setCellValue(record.getClient().getEnterprise());
                //联系方式
                dataRow.createCell(10).setCellValue(record.getClient().getClientPhone());
                // 入库库数量
                dataRow.createCell(6).setCellValue(record.getGnum());

                // 应用数据样式
                for (int j = 0; j < headers.length; j++) {
                    dataRow.getCell(j).setCellStyle(dataStyle);
                }
            }
        }

        // 写入文件
        try {
            workbook.write(os);
        } finally {
            workbook.close();
        }
    }

    //库存总量
    public double getAlertItems() {
        return inOutDao.getAlertItems();
    }

    //库存总量变化趋势
    public double getAlertTrend() {
        double growthRate = 0;
        // 从数据库获取按月统计结果// 按年月统计库存总量
        List<MonthCount> monthCounts = inOutDao.getAlertTrend();
        // 转换为Map // 存储每月库存总量
        Map<String, Integer> monthlyCounts = new HashMap<>();
        for (MonthCount mc : monthCounts) {
            monthlyCounts.put(mc.getYearMonth(), mc.getNums());
        }
        // 按月排序并计算环比
        List<String> sortedMonths = new ArrayList<>(monthlyCounts.keySet());
        Collections.sort(sortedMonths);
        for (int i = 1; i < sortedMonths.size(); i++) {
            String currentMonth = sortedMonths.get(i);
            String prevMonth = sortedMonths.get(i - 1);
            int currentCount = monthlyCounts.get(currentMonth);
            int prevCount = monthlyCounts.get(prevMonth);
            growthRate = ((double) currentCount / prevCount - 1)*100;
            System.out.printf("%s月 vs %s月: 库存总量 %d vs %d, 环比增长: %.2f%%%n",
                    currentMonth, prevMonth, currentCount, prevCount, growthRate);
        }
        return growthRate;
    }

}
